/*
 * @Author: yangzonglong
 * @Date: 2023-01-04 13:47:18
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-10-07 10:51:07
 * @Auditor: 
 */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState, useImperativeHandle, forwardRef, useMemo } from 'react';
import { FormItemProps } from '../components/InputFormItemController';
import { Form, Input } from 'antd';
import moment from 'moment';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import { execCodingRuleApi } from './api';
import styles from './styles.module.scss';

export interface OrderNumberProps extends CanvasItemProps {
  initialValue?: string;
  isDesign?: boolean;
  formItemProps?: FormItemProps;
  orderNumberProps?: { ruleCode: string; customStyleFlag?: boolean; };
  style?: React.CSSProperties;
}
interface RefProps {
  getData(): Promise<string>;
}

const OrderNumber = (props: OrderNumberProps, ref: React.Ref<RefProps>) => {
  const { initialValue, orderNumberProps: _orderNumberProps, formItemProps, domComplete, isDesign, ...canvasProps } = props;

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  const [value, setValue] = useState<string>('');

  const orderNumberProps = useMemo(() => _orderNumberProps ? _orderNumberProps : { ruleCode: undefined }, [_orderNumberProps]);

  useEffect(() => {
    if (initialValue) return setValue(initialValue);
    // if (orderNumberProps?.ruleCode && !isDesign) {
    //   execCodingRuleApi({
    //     type: '20',
    //     count: 1,
    //     ruleCode: orderNumberProps.ruleCode as string,
    //     data: {},
    //   }).then(res => setValue(res[0]))
    // } else {
    //   setValue(moment().format('YYYYMMDDHHmmss'))
    // }
  }, [initialValue,]);

  useImperativeHandle(ref, () => ({
    getData: async () => {
      if (value) return value;
      if (!orderNumberProps.ruleCode) return moment().format('YYYYMMDDHHmmss');

      const res = await execCodingRuleApi({
        type: '20',
        count: 1,
        ruleCode: orderNumberProps.ruleCode as string,
        data: { _temp_: 1 },
      });

      setValue(res?.[0]);
      return res?.[0] || value || false;
    },
    getDataNotCheck: () => {
      return value
    },
    setData: (v: string) => {
      if (v) {
        setValue(v);
      }
    }
  }));

  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;

  return !_orderNumberProps?.customStyleFlag ? (
    <Form.Item {...canvasProps} {...formItemProps} label={label}>
      <div>
        <Input disabled value={value} />
      </div>
    </Form.Item>
  ) : (
    <div
      className={isDesign ? styles.design : styles.odnum}
      {...canvasProps}
      style={{ ...formItemProps?.style, ...props.style }}>
      {label}{value}
    </div>
  );
};

export default forwardRef(OrderNumber);